//
//  KUserAuthenticationVC.m
//  Keping
//
//  Created by Joanlove on 2017/12/21.
//  Copyright © 2017年 柯平. All rights reserved.
//

#import "KUserAuthenticationVC.h"
#import "KBaeTFCell.h"
#import "KUserAuthenticationAddressCell.h"
#import "KUserAuthenticationPhotoCell.h"
#import <TZImagePickerController/TZImagePickerController.h>
#import <TZImagePickerController/TZImageManager.h>
#import "KUploadImageRequest.h"
#import "KUpdateProfileRequest.h"
#import "KUserData.h"

@interface KUserAuthenticationVC () {
    NSArray *items;
}

@property (nonatomic, strong) NSMutableDictionary *userAuthenticationDict;
@property (nonatomic, strong) KPartyView *partyView;

@end

@implementation KUserAuthenticationVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    items = @[@[@"*Full Name:"],@[@"*Adress:"],@[@"*IC NO:"],@[@"*IC Photo:"]];
    self.groupView.refreshEnable = NO;
    self.groupView.loadmoreEnable = NO;
    self.groupView.sectionHeaderHeight = 10.0;
    [self.groupView registerNib:[UINib nibWithNibName:[KBaeTFCell className] bundle:nil] forCellReuseIdentifier:[KBaeTFCell className]];
    [self.groupView registerNib:[UINib nibWithNibName:[KUserAuthenticationAddressCell className] bundle:nil] forCellReuseIdentifier:[KUserAuthenticationAddressCell className]];
    [self.groupView registerNib:[UINib nibWithNibName:[KUserAuthenticationPhotoCell className] bundle:nil] forCellReuseIdentifier:[KUserAuthenticationPhotoCell className]];
    self.partyView = [KPartyView unarchive];
    [self getData];
}

- (void)getData {
    [super getData];
    [self showLoading];
    WEAKSELF
    KUserVeritifyRequest *request = [[KUserVeritifyRequest alloc] init];
    [request startWithCompletionBlockWithSuccess:^(__kindof KBaseRequest * _Nonnull request) {
        [weakSelf hideHUD];
        NSDictionary *dict = request.responseObject;
        NSInteger statusCode = [[dict objectForKey:@"statusCode"] integerValue];
        if (statusCode == 200) {
            weakSelf.userAuthenticationDict = [[dict objectForKey:@"authenticationView"] mutableCopy];
            [weakSelf.groupView reloadData];
        } else {
            [weakSelf showErrorText:[dict objectForKey:@"msg"] errCode:statusCode];
        }
    } failure:^(__kindof KBaseRequest * _Nonnull request) {
        
    }];
}

- (NSMutableDictionary *)userAuthenticationDict {
    if (!_userAuthenticationDict) {
        _userAuthenticationDict = [NSMutableDictionary new];
    }
    return _userAuthenticationDict;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return items.count;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSInteger section = indexPath.section;
    CGFloat height;
    switch (section) {
        case 0:
        case 2:
            height = 44.0;
            break;
        case 1:
            height = 120.0;
            break;
        case 3:
            height = 180.0;
            break;
        default:
            height = 44.0;
            break;
    }
    return height;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    if (section == 3) {
        return 80.0;
    }
    return 0.0001;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger section = indexPath.section;
    UITableViewCell *cell;
    WEAKSELF
    switch (section) {
        case 0:
        case 2:
        {
            KBaeTFCell *base = [tableView dequeueReusableCellWithIdentifier:[KBaeTFCell className]];
            base.title.text = [[items objectAtIndex:section] objectAtIndex:0];
            base.textBlock = ^(NSString *text) {
                if (section == 0) {
                    [weakSelf.userAuthenticationDict setObject:text forKey:@"realyName"];
                } else {
                    [weakSelf.userAuthenticationDict setObject:text forKey:@"icNo"];
                }
            };
            if (self.partyView.identityAuthentication) {
                base.connect.userInteractionEnabled = NO;
            } else {
                base.connect.userInteractionEnabled = YES;
            }
            if (section == 0) {
                base.connect.text = [self.userAuthenticationDict objectForKey:@"realyName"];
            } else {
                base.connect.text = [self.userAuthenticationDict objectForKey:@"icNo"];
            }
            base.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            cell = base;
        }
            break;
        case 1:
        {
            KUserAuthenticationAddressCell *address = [tableView dequeueReusableCellWithIdentifier:[KUserAuthenticationAddressCell className]];
            address.title.text = [[items objectAtIndex:section] objectAtIndex:0];
            address.textBlock = ^(NSString *text) {
                [weakSelf.userAuthenticationDict setObject:text forKey:@"address"];
            };
            if (self.partyView.identityAuthentication) {
                address.connect.userInteractionEnabled = NO;
            } else {
                address.connect.userInteractionEnabled = YES;
            }
            address.connect.text = [self.userAuthenticationDict objectForKey:@"address"];
            address.accessoryType = UITableViewCellAccessoryNone;
            cell = address;
        }
            break;
        case 3:
        {
            KUserAuthenticationPhotoCell *photo = [tableView dequeueReusableCellWithIdentifier:[KUserAuthenticationPhotoCell className]];
            photo.title.text = [[items objectAtIndex:section] objectAtIndex:0];
            photo.actionForPhotoAlum = ^(NSInteger index) {
                [weakSelf selectionForPhoto:index];
            };
            if (self.partyView.identityAuthentication) {
                photo.front.userInteractionEnabled = NO;
                photo.back.userInteractionEnabled = NO;
            } else {
                photo.front.userInteractionEnabled = YES;
                photo.back.userInteractionEnabled = YES;
            }
            photo.userAuthenticationDict = [self.userAuthenticationDict copy];
            photo.accessoryType = UITableViewCellAccessoryNone;
            cell = photo;
        }
            break;
        default:
            break;
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    if (section == 3) {
        UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 80)];
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 10, kScreenWidth, 10)];
        label.text = @"*IC registration is needed when using pre-appointment feature";
        label.textColor = RGBCOLOR(190, 190, 190);
        label.font = [UIFont systemFontOfSize:10];
        [footerView addSubview:label];
        
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(15, CGRectGetMaxY(label.frame) + 20, kScreenWidth - 30, 44);
        [button setTitle:@"Submit" forState:UIControlStateNormal];
        button.titleLabel.font = SystemFont;
        button.titleLabel.textColor = kWhiteColor;
        button.backgroundColor = RGBCOLOR(125, 82, 248);
        button.centerX = footerView.centerX;
        button.layer.masksToBounds = YES;
        button.layer.cornerRadius  = 20.0;
        [button addTarget:self action:@selector(pushDynamics) forControlEvents:UIControlEventTouchUpInside];
        [footerView addSubview:button];
        return footerView;
    }
    return nil;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (void)selectionForPhoto:(NSInteger)index {
    WEAKSELF
    TZImagePickerController *imagePickerVC = [[TZImagePickerController alloc] initWithMaxImagesCount:1 delegate:nil];
    imagePickerVC.allowPickingVideo = NO;
    [imagePickerVC setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        if (index == 100) {
            [weakSelf.userAuthenticationDict setObject:assets forKey:@"icPhotoFront"];
        } else {
            [weakSelf.userAuthenticationDict setObject:assets forKey:@"icPhotoBack"];
        }
        [weakSelf.groupView reloadData];
    }];
    [self presentViewController:imagePickerVC animated:YES completion:nil];
}

- (void)pushDynamics {
    if (![[self.userAuthenticationDict objectForKey:@"realyName"] isNotBlank]) {
        [self showErrorText:@"Full Name is not null!"];
        return;
    }
    if (![[self.userAuthenticationDict objectForKey:@"icNo"] isNotBlank]) {
        [self showErrorText:@"IC NO is not null!"];
        return;
    }
    
    if (![[self.userAuthenticationDict objectForKey:@"address"] isNotBlank]) {
        [self showErrorText:@"Address is not null!"];
        return;
    }
    
    if (![self.userAuthenticationDict objectForKey:@"icPhotoFront"]) {
        [self showErrorText:@"Front photo is not null!"];
        return;
    }
    
    if (![self.userAuthenticationDict objectForKey:@"icPhotoBack"]) {
        [self showErrorText:@"Back photo is not null!"];
        return;
    }
    
    [self showLoading];
    WEAKSELF
    dispatch_group_t group = dispatch_group_create();
    for (int i = 0; i < 2; i++) {
        dispatch_group_enter(group);
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            TZAssetModel *model;
            if (i == 0) {
                model = [[weakSelf.userAuthenticationDict objectForKey:@"icPhotoFront"] firstObject];
            } else {
                model = [[weakSelf.userAuthenticationDict objectForKey:@"icPhotoBack"] firstObject];
            }
            [[TZImageManager alloc] getOriginalPhotoWithAsset:model completion:^(UIImage *photo, NSDictionary *info) {
                KUploadImageRequest* imgRequest = [[KUploadImageRequest alloc] initWithUploadImage:photo compression:0.5];
                [imgRequest startWithCompletionBlockWithSuccess:^(__kindof KBaseRequest * _Nonnull request) {
                    NSDictionary *dict = request.responseObject;
                    NSInteger statusCode = [[dict objectForKey:@"statusCode"] integerValue];
                    if (statusCode == 200) {
                        if (i == 0) {
                            [weakSelf.userAuthenticationDict removeObjectForKey:@"icPhotoFront"];
                            [weakSelf.userAuthenticationDict setObject:[dict objectForKey:@"imageUrl"] forKey:@"icPhotoFront"];
                        } else {
                            [weakSelf.userAuthenticationDict removeObjectForKey:@"icPhotoBack"];
                            [weakSelf.userAuthenticationDict setObject:[dict objectForKey:@"imageUrl"] forKey:@"icPhotoBack"];
                        }
                    }
                    dispatch_group_leave(group);
                } failure:^(__kindof KBaseRequest * _Nonnull request) {
                    dispatch_group_leave(group);
                }];
            }];
            
        });
    }
    
    
    dispatch_group_notify(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        KUserAuthenticationRequest *request = [[KUserAuthenticationRequest alloc] init];
        request.params = weakSelf.userAuthenticationDict;
        [request startWithCompletionBlockWithSuccess:^(__kindof KBaseRequest * _Nonnull request) {
            [weakSelf hideHUD];
            NSDictionary *dict = request.responseObject;
            NSInteger statusCode = [[dict objectForKey:@"statusCode"] integerValue];
            if (statusCode == 200) {
                KLog(@"%@",dict);
                [weakSelf showSuccess:[dict objectForKey:@"msg"]];
                [weakSelf.navigationController popViewControllerAnimated:YES];
            } else {
                [weakSelf showErrorText:[dict objectForKey:@"msg"] errCode:statusCode];
            }
        } failure:^(__kindof KBaseRequest * _Nonnull request) {
            [weakSelf hideHUD];
            [weakSelf showError:request.error];
        }];
    });
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
